<template>
  <div class="container">
    <a-space direction="vertical" style="width: 100%" :size="16">
      <a-card style="width: 100%" title="商品管理">
        <a-form :model="formState">
          <a-row>
            <a-col :span="4">
              <a-form-item label="商品名称">
                <a-input
                  style="width: 80%"
                  v-model:value="formState.brandName"
                  placeholder="输入商品名称关键词"
                />
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="商品编号">
                <a-input
                  style="width: 80%"
                  v-model:value="formState.number"
                  placeholder="输入商品编号"
                />
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="所属品牌">
                <a-input
                  style="width: 80%"
                  v-model:value="formState.searchCondition"
                  placeholder="输入商品品牌"
                />
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="商品类目">
                <a-select
                  ref="select"
                  v-model:value="formState.typeId"
                  style="width: 80%"
                  placeholder="商品类目"
                  @change="handleChangeType"
                >
                  <a-select-option :value="0">全部</a-select-option>
                  <a-select-option
                    v-for="item in goodsTypeList"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="子类目">
                <a-select
                  ref="select"
                  v-model:value="formState.subTypeId"
                  style="width: 80%"
                  placeholder="商品子类目"
                >
                  <a-select-option :value="0">全部</a-select-option>
                  <template
                    v-if="
                      subcategoryList[0] &&
                      subcategoryList[0].childrenList.length > 0
                    "
                  >
                    <a-select-option
                      v-for="item in subcategoryList[0].childrenList"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-select-option
                    >
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="成色">
                <a-select
                  ref="select"
                  v-model:value="formState.finenessId"
                  style="width: 80%"
                  placeholder="商品成色"
                >
                  <a-select-option :value="null">全部</a-select-option>
                  <a-select-option
                    v-for="item in goodsFinenessList"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.content }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="商品状态">
                <a-select
                  ref="select"
                  v-model:value="formState.status"
                  style="width: 80%"
                  placeholder="商品状态"
                >
                  <a-select-option :value="-1">全部</a-select-option>
                  <a-select-option
                    :value="item.value"
                    v-for="(item, index) in goodsStateEnum.data"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <div class="layout-flexSpace">
          <a-space wrap>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
          <a-space wrap>
            <a-button type="primary" @click="handleExport">导出</a-button>
            <a-button @click="goodsListOpenFunc">出售商品</a-button>
          </a-space>
        </div>
      </a-card>

      <a-card>
        <a-table
          :dataSource="dataSource"
          :columns="goodsColumns"
          :pagination="pagination"
          @change="handleChangeTable"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <div style="display: flex; align-items: center">
                <a-image
                  :src="record.coverPic"
                  :preview="{
                    src: record.coverPic,
                  }"
                  :width="60"
                />
                <div style="margin-left: 20px">
                  <div>{{ record.name }}</div>
                  <div>商品编号：{{ record.sku }}</div>
                </div>
              </div>
            </template>

            <template v-if="column.key === 'shopPrice'">
              ￥{{ record.shopPrice }}
            </template>
            <template v-if="column.key === 'isSale'">
              {{
                record.isSale == 1
                  ? "已售出"
                  : record.isShelf == 1
                  ? "已上架"
                  : "未上架"
              }}
            </template>
            <template v-if="column.key === 'operate'">
              <a-space wrap>
                <a-button type="primary" @click="seeFunc(record.id)"
                  >查看</a-button
                >
                <a-popconfirm
                  title="是否确定要下架该商品?"
                  ok-text="是"
                  cancel-text="否"
                  v-if="record.isShelf == 1 && record.isSale == 0"
                  @confirm="handleSell(record.id, 1)"
                >
                  <a-button>下架</a-button>
                </a-popconfirm>
                <template v-if="record.isSale == 0">
                  <a-button type="primary" @click="handleEdit(record.id)"
                    >编辑</a-button
                  >
                  <a-popconfirm
                    title="是否确定要上架该商品?"
                    ok-text="是"
                    cancel-text="否"
                    v-if="record.isShelf == 0"
                    @confirm="handleSell(record.id, 2)"
                  >
                    <a-button>上架</a-button>
                  </a-popconfirm>
                  <a-popconfirm
                    title="是否要删除该数据?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="confirm(record.id)"
                  >
                    <a-button type="primary" danger>删除</a-button>
                  </a-popconfirm>
                </template>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-space>

    <a-modal
      v-model:open="goodsListOpen"
      title="出售商品"
      :footer="null"
      width="50%"
    >
      <a-space direction="vertical" style="width: 100%" :size="16">
        <div class="layout-flexSpace">
          <a-input-search
            v-model:value="params.searchCondition"
            placeholder="请输入商品名称关键字查询"
            enter-button="查询"
            :size="16"
            style="width: 50%"
            @search="onSearch"
          />
          <a-button type="primary" @click="applicationFunc">申请类目</a-button>
        </div>
        <div class="list-scroll" style="height: 450px">
          <a-space direction="vertical" style="width: 100%" :size="16">
            <template v-for="(item, key, index) in platList" :key="index">
              <a-alert :message="key" type="info" />
              <div
                style="display: flex; align-items: center; cursor: pointer"
                v-for="(opt, indexs) in item"
                :key="indexs"
                @click="addFunc(opt.id)"
              >
                <a-avatar :size="30" :src="opt.coverPic"></a-avatar>
                <div style="margin-left: 6px">
                  {{ opt.brandName }}/{{ opt.name }}
                </div>
              </div>
            </template>
          </a-space>
        </div>
        <a
          v-if="platTotal >= params.page * params.pageSize"
          @click="handleLoadMore"
          style="text-align: center; display: block"
          >加载更多</a
        >
      </a-space>
    </a-modal>
    <!-- 商品详情 -->
    <see ref="seeRef"></see>
    <!-- 添加商品 -->
    <add ref="addRef" @reflashList="reflashList"></add>
    <!-- 未设置地址提示弹窗 -->
    <addressModal ref="addressModalRef"></addressModal>

    <!-- 申请类目 -->
    <applicationGoods ref="applicationGoodsRef"></applicationGoods>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { goodsColumns } from "./columns";
import goodsStateEnum from "@/enums/goodsStateEnum";
import see from "./goodsManageModule/see.vue";
import add from "./goodsManageModule/add.vue";
import addressModal from "../../components/addressModal.vue";
import applicationGoods from "./categoryApplyForModule/applicationGoods.vue";
import { goodsType, goodsFineness } from "@/api/order";
import { queryUserAddressList } from "@/api/config";
import { exporeFile } from "@/utils/exporeFile";
import {
  goodsList,
  exportGoods,
  deleteGoods,
  editStatus,
  goodsSearchList,
} from "@/api/goods";

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal:total => `共 ${total} 条`
});
const formState = ref({
  page: pagination.value.current,
  pageSize: pagination.value.pageSize,
  brandId: undefined,
  brandName: undefined,
  finenessId: undefined,
  number: undefined,
  status: undefined,
  subTypeId: undefined,
  typeId: undefined,
  searchCondition: undefined,
});
const dataSource = ref([]);

//查看详情
const seeRef = ref(null);
const seeFunc = (id) => {
  seeRef.value.seeFunc(id);
};

//出售商品
const goodsListOpen = ref(false);
const addressModalRef = ref(null);
const goodsListOpenFunc = () => {
  if (!isHasAddress.value) {
    oldPlatList.value = [];
    params.value.page = 1;
    getGoodsSearchList();
    goodsListOpen.value = true;
  } else {
    addressModalRef.value.modalOpen = true;
  }
};
const isHasAddress = ref(true);
const queryUserAddressListFn = async () => {
  const result = await queryUserAddressList({ page: 1, pageSize: 1 });
  if (result.code === 200) {
    isHasAddress.value = result.data.list.length == 0;
  }
};
// 上下架
const handleSell = async (id, status) => {
  const result = await editStatus({ id, status });
  if (result.code == 200) {
    getGoodsList();
  }
};
const handleExport = async () => {
  const data = await exportGoods(formState.value);
  exporeFile("商品管理列表.xls", data);
};
const applicationGoodsRef = ref(false);
const applicationFunc = () => {
  applicationGoodsRef.value.open(0);
};

//打开添加商品抽屉
const addRef = ref(null);
const addFunc = (id) => {
  addRef.value.addFunc(id, "add");
  // goodsListOpen.value = false;
};
const handleEdit = (id) => {
  addRef.value.addFunc(id, "edit");
}
function handleSearch() {
  getGoodsList();
}
function handleReset() {
  formState.value = {
    page: 1,
    pageSize: 10,
    brandId: undefined,
    brandName: undefined,
    finenessId: undefined,
    number: undefined,
    status: undefined,
    subTypeId: undefined,
    typeId: undefined,
    searchCondition: undefined,
  };
  getGoodsList();
}

const confirm = async (id) => {
  const result = await deleteGoods({ id: id });
  if (result.code == 200) {
    message.info("删除成功");
    getGoodsList();
  }
};

const goodsTypeList = ref([]);
const getGoodsType = async () => {
  const result = await goodsType();
  if (result.code == 200) {
    goodsTypeList.value = result.data;
  }
};
const goodsFinenessList = ref([]);
const getGoodsFineness = async () => {
  const result = await goodsFineness();
  if (result.code == 200) {
    goodsFinenessList.value = result.data;
  }
};
const subcategoryList = ref([]);
function handleChangeType(val) {
  formState.value.subTypeId = undefined;
  subcategoryList.value = goodsTypeList.value.filter(
    (value) => value.id == val
  );
}
const getGoodsList = async () => {
  const result = await goodsList(formState.value);
  if (result.code == 200) {
    dataSource.value = result.data.list;
    pagination.value.total = result.data.total;
  }
};
const searchCondition = ref("");
const platList = ref([]);
const oldPlatList = ref([]);
const platTotal = ref(0);
const params = ref({
  page: 1,
  pageSize: 5,
  searchCondition: undefined,
});
function handleLoadMore() {
  if (params.value.page * params.value.pageSize >= platTotal.value) return;
  params.value.page++;
  getGoodsSearchList();
}
//商品查询
const onSearch = () => {
  oldPlatList.value = [];
  params.value.page = 1;
  getGoodsSearchList();
};
const getGoodsSearchList = async () => {
  const result = await goodsSearchList(params.value);
  if (result.code == 200) {
    oldPlatList.value = [...oldPlatList.value, ...result.data.list];
    platTotal.value = result.data.total;
    const groupByCategory = oldPlatList.value.reduce((group, product) => {
      const { firstLetter } = product;
      group[firstLetter] = group[firstLetter] ?? [];
      group[firstLetter].push(product);
      return group;
    }, {});
    platList.value = groupByCategory;
  }
};
// 刷新页面
function reflashList() {
  goodsListOpen.value = false;
  getGoodsList();
}
// 分页
const handleChangeTable = (pagina) => {
  pagination.value = {...pagination.value,...pagina};
  formState.value.page = pagina.current;
  formState.value.pageSize = pagina.pageSize;
  getGoodsList();
}
onMounted(() => {
  queryUserAddressListFn();
  getGoodsType();
  getGoodsFineness();
  getGoodsList();
});
</script>

<style lang="less"></style>
